package com.wangchao.excletransform.code.service;

import com.wangchao.excletransform.code.vo.originDataVo;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.StandardMultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import jxl.Workbook;
@Service
public class ExcleTransformService {

    private  List<originDataVo> list = new ArrayList<>();

    public Map<String,String> uploadFile(HttpServletRequest request){
        list.clear();
        Map<String,String> map = new HashMap<>(2);
        try {
        StandardMultipartHttpServletRequest req = (StandardMultipartHttpServletRequest) request;
        List<MultipartFile> files = req.getFiles("file");
        File tmpFile = new File(System.getProperty("java.io.tmpdir") + System.getProperty("file.separator") + "temp.xlsx");
        files.get(0).transferTo(tmpFile);
        WritableWorkbook workbook = Workbook.createWorkbook(tmpFile);
        WritableSheet sheet =  workbook.getSheet(1);
            int rows = sheet.getRows();
             for (int i=1;i<rows;i++) {
                 if (!StringUtils.isEmpty(sheet.getWritableCell(9,i).getContents())){
                     originDataVo vo = new originDataVo();
                     vo.setCode(sheet.getWritableCell(10,i).getContents());
                     vo.setName(sheet.getWritableCell(9,i).getContents());
                     vo.setParentName(sheet.getWritableCell(7,i).getContents());
                     vo.setParentCode(sheet.getWritableCell(8,i).getContents());
                     vo.setLevel("4");
                     list.add(vo);
                 }
                 if (!StringUtils.isEmpty(sheet.getWritableCell(11,i).getContents())){
                     originDataVo vo = new originDataVo();
                     vo.setCode(sheet.getWritableCell(12,i).getContents());
                     vo.setName(sheet.getWritableCell(11,i).getContents());
                     vo.setParentName(sheet.getWritableCell(9,i).getContents());
                     vo.setParentCode(sheet.getWritableCell(10,i).getContents());
                     vo.setLevel("5");
                     list.add(vo);
                 }
            }
            tmpFile.delete();
            workbook.close();
        } catch (IOException | WriteException e) {
            e.printStackTrace();
            map.put("result","0");
            map.put("message","出错了，请稍后再试······");
        }finally {
        }
        map.put("result","1");
        map.put("message","上传成功");
        return map;
    }
}
